<template>
  <div class="class-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的班级</span>
          <el-button type="primary" @click="openCreateDialog">创建新班级</el-button>
        </div>
      </template>
      <el-table v-loading="loading" :data="classList" stripe>
        <el-table-column label="班级名称" prop="className" />
        <el-table-column label="学科" prop="subject" />
        <el-table-column label="邀请码" prop="invitationCode" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope"
            >{{ new Date(scope.row.createdAt).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="viewStudents(scope.row)">查看学生</el-button>
            <el-button size="small" type="primary" @click="openAssignDialog(scope.row)"
              >布置作业</el-button
            >
            <el-button size="small" type="success" @click="viewAssignments(scope.row)"
              >查看作业</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建班级对话框 -->
    <el-dialog
      v-model="createClassDialogVisible"
      title="创建新班级"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createClassForm"
        :rules="createFormRules"
        label-width="80px"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="createClassForm.className" placeholder="例如：高三（2）班" />
        </el-form-item>
        <el-form-item label="学科" prop="subject">
          <el-select v-model="createClassForm.subject" placeholder="请选择学科">
            <el-option
              v-for="subject in AllSubjects"
              :key="subject"
              :label="subject"
              :value="subject"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="createClassForm.description"
            placeholder="请输入班级描述（可选）"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createClassDialogVisible = false">取消</el-button>
        <el-button :loading="createLoading" type="primary" @click="handleCreateClass"
          >确认创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看学生对话框 -->
    <el-dialog v-model="viewStudentsDialogVisible" title="班级学生名单" width="600px">
      <el-table v-loading="studentLoading" :data="studentList" stripe>
        <el-table-column label="学生姓名" prop="nickname" />
        <el-table-column label="加入日期" width="200">
          <template #default="scope">{{ new Date(scope.row.joinDate).toLocaleString() }}</template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 布置作业对话框 -->
    <el-dialog v-model="assignDialogVisible" title="布置新作业" top="5vh" width="70%">
      <el-form ref="assignFormRef" :model="assignForm" :rules="assignFormRules" label-width="100px">
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="assignForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="assignForm.deadline"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择截止日期"
            type="datetime"
            value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
          />
        </el-form-item>
        <el-form-item label="作业描述">
          <el-input
            v-model="assignForm.description"
            placeholder="请输入作业描述或要求"
            type="textarea"
          />
        </el-form-item>

        <!-- 搜索关键词 -->
        <el-form-item label="题库筛选" style="margin-bottom: 10px">
          <el-input
            v-model="questionFilter.keyword"
            clearable
            placeholder="输入题目关键词"
            style="width: 300px"
            @keyup.enter="fetchQuestions"
          />
          <el-button style="margin-left: 10px" type="primary" @click="fetchQuestions"
            >搜索</el-button
          >
        </el-form-item>

        <!-- 题目列表 -->
        <el-form-item label="选择题目" prop="questionIds">
          <el-table
            ref="questionTableRef"
            v-loading="questionLoading"
            :data="allQuestions"
            height="300"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="题目内容" prop="content" show-overflow-tooltip>
              <template #default="{ row }">
                <div v-html="renderMarkdown(row.content)"></div>
              </template>
            </el-table-column>
            <el-table-column label="类型" prop="type" width="120" />
            <el-table-column label="难度" prop="difficulty" width="80" />
          </el-table>
          <el-pagination
            :current-page="questionPage.current"
            :page-size="questionPage.size"
            :total="questionPage.total"
            background
            layout="prev, pager, next"
            style="margin-top: 10px; text-align: right"
            @current-change="handlePageChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button :loading="assignLoading" type="primary" @click="handleAssignHomework"
          >确认布置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { useAuthStore } from '@/stores/authStore.ts'
import type { ElTable, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { AllSubjects, renderMarkdown } from '@/api/utils.ts'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(true)

const classList = ref<any[]>([])
const createLoading = ref(false)
const createClassDialogVisible = ref(false)
const createFormRef = ref<FormInstance>()
const createClassForm = reactive({
  className: '',
  subject: '',
  description: '',
})
const createFormRules = reactive<FormRules>({
  className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
})

const viewAssignments = (myClass) => {
  router.push({ name: 'AssignmentList', params: { classId: myClass.classId } })
}

const viewStudentsDialogVisible = ref(false)
const studentList = ref([])
const studentLoading = ref(false)
const assignDialogVisible = ref(false)
const assignLoading = ref(false)
const questionLoading = ref(false)
const allQuestions = ref<any[]>([])
const questionTableRef = ref<InstanceType<typeof ElTable>>()
const assignFormRef = ref<FormInstance>()
const assignForm = reactive({
  classId: null as number | null,
  title: '',
  description: '',
  deadline: '',
  questionIds: [] as number[],
})
const assignFormRules = reactive<FormRules>({
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
  questionIds: [
    { type: 'array', required: true, min: 1, message: '请至少选择一道题目', trigger: 'change' },
  ],
})

const currentClassSubject = ref('')
const questionFilter = reactive({
  keyword: '',
})
const questionPage = reactive({
  current: 1,
  size: 10,
  total: 0,
})

const fetchQuestions = async () => {
  questionLoading.value = true
  try {
    const params: Record<string, any> = {
      subject: currentClassSubject.value,
    }
    if (questionFilter.keyword) {
      params.keyword = questionFilter.keyword
    }
    const response = await apiClient.get(`/teacher/questions/${questionPage.current}`, {
      params,
    })
    allQuestions.value = response.data.data
    questionPage.total = response.data.total
  } catch (error) {
    handleErrorAndRedirect(error, '加载题库失败')
  } finally {
    questionLoading.value = false
  }
}

const handlePageChange = (newPage: number) => {
  questionPage.current = newPage
  fetchQuestions()
}

const fetchClasses = async () => {
  loading.value = true
  try {
    await authStore.initialize()

    if (!authStore.isTeacher) {
      loading.value = false
      return
    }
    const response = await apiClient.get('/classes/my-classes')
    classList.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取班级列表失败')
  } finally {
    loading.value = false
  }
}

const openCreateDialog = () => {
  createClassDialogVisible.value = true
}

const resetCreateForm = () => {
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
}

const handleCreateClass = async () => {
  if (!createFormRef.value) return
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      createLoading.value = true
      try {
        await apiClient.post('/classes', createClassForm)
        ElMessage.success('班级创建成功！')
        createClassDialogVisible.value = false
        await fetchClasses()
      } catch (error) {
        handleErrorAndRedirect(error, '创建失败，请检查输入或联系管理员')
      } finally {
        createLoading.value = false
      }
    } else {
      ElMessage.warning('请填写所有必填项')
    }
  })
}

const viewStudents = async (classRow: any) => {
  viewStudentsDialogVisible.value = true
  studentLoading.value = true
  studentList.value = []
  try {
    const response = await apiClient.get(`/classes/${classRow.classId}/students`)
    studentList.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取学生列表失败')
  } finally {
    studentLoading.value = false
  }
}

const openAssignDialog = async (classRow: any) => {
  if (assignFormRef.value) {
    assignFormRef.value.resetFields()
  }
  Object.assign(assignForm, {
    classId: classRow.classId,
    title: '',
    description: '',
    deadline: '',
    questionIds: [],
  })

  currentClassSubject.value = classRow.subject
  questionPage.current = 1
  questionFilter.keyword = ''

  assignDialogVisible.value = true

  await fetchQuestions()
}

const handleSelectionChange = (val: any[]) => {
  assignForm.questionIds = val.map((item) => item.questionId)
  if (assignFormRef.value) {
    assignFormRef.value.validateField('questionIds')
  }
}

const handleAssignHomework = async () => {
  if (!assignFormRef.value) return
  await assignFormRef.value.validate(async (valid) => {
    if (valid) {
      assignLoading.value = true
      try {
        await apiClient.post('/assignments', assignForm)
        ElMessage.success('作业布置成功！')
        assignDialogVisible.value = false
      } catch (error) {
        handleErrorAndRedirect(error, '作业布置失败')
      } finally {
        assignLoading.value = false
      }
    } else {
      ElMessage.warning('请填写完整的作业信息并选择题目')
    }
  })
}

onMounted(fetchClasses)
</script>

<style scoped>
.class-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
